package com.fxsh168.server.services;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.baidu.trace.OnEntityListener;
import com.baidu.trace.OnStartTraceListener;
import com.baidu.trace.OnStopTraceListener;
import com.baidu.trace.OnTrackListener;
import com.baidu.trace.TraceLocation;
import com.fxsh168.server.interfaces.Constant;
import com.fxsh168.server.maps.yinyan.DateUtils;
import com.fxsh168.server.maps.yinyan.MonitorService;
import com.fxsh168.server.maps.yinyan.TrackReceiver;
import com.fxsh168.server.otherviews.banner.MyApplication;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import okhttp3.Call;


public class TraceUpService extends Service {
    boolean isTraceStarted = false;
    private MyApplication trackApp = null;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        trackApp = (MyApplication) getApplicationContext();
        aboutYing();
    }


    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        trackApp.getClient().onDestroy();
    }

    //   关于鹰眼服务的全部初始化
    public void aboutYing() {
        //       关于鹰眼服务的---------------------------------------------------
        init();           // 初始化
        initListener();     // 初始化监听器
        setInterval();      // 设置采集周期
        setRequestType();    // 设置http请求协议类型
    }

    //    * 设置采集周期和打包周期
    private void setInterval() {
        trackApp.getClient().setInterval(gatherInterval, packInterval);
    }


    //     * 设置请求协议
    protected void setRequestType() {
        int type = 0;
        trackApp.getClient().setProtocolType(type);
    }

    //    ----------------------------------鹰眼轨迹----------------------------------
    protected static OnStartTraceListener startTraceListener = null; //   * 开启轨迹服务监听器
    protected static OnStopTraceListener stopTraceListener = null;   //     * 停止轨迹服务监听器
    protected RefreshThread refreshThread = null;      //  * 刷新地图线程(获取实时点)
    private int packInterval = 15;   // * 打包周期（单位 : 秒）
    private static OnEntityListener entityListener = null;      //  * Entity监听器
    private int gatherInterval = 5;  //     * 采集周期（单位 : 秒）
    private Intent serviceIntent = null;
    private static boolean isRegister = false;
    protected static PowerManager pm = null;
    private TrackReceiver trackReceiver = new TrackReceiver();
    public static PowerManager.WakeLock wakeLock = null;

    public void init() {
        Toast.makeText(this, "正在开启轨迹服务，请稍候", Toast.LENGTH_SHORT).show();
        startTrace();
        if (!isRegister) {
            if (null == pm) {
                pm = (PowerManager) trackApp.getSystemService(Context.POWER_SERVICE);
            }
            if (null == wakeLock) {
                wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "track upload");
            }
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            filter.addAction(Intent.ACTION_SCREEN_ON);
            filter.addAction("com.baidu.trace.action.GPS_STATUS");
            trackApp.registerReceiver(trackReceiver, filter);
            isRegister = true;
        }
    }
//     * 初始化监听器

    private void initListener() {
        // 初始化开启轨迹服务监听器
        if (null == startTraceListener) {
            initOnStartTraceListener();
        }

        // 初始化停止轨迹服务监听器
        if (null == stopTraceListener) {
            initOnStopTraceListener();
        }

        // 初始化entity监听器
        if (null == entityListener) {
            initOnEntityListener();
        }
    }

    /**
     * 初始化OnStartTraceListener
     */
    private void initOnStartTraceListener() {
        // 初始化startTraceListener
        startTraceListener = new OnStartTraceListener() {
            // 开启轨迹服务回调接口（arg0 : 消息编码，arg1 : 消息内容，详情查看类参考）
            public void onTraceCallback(int arg0, String arg1) {
//                mHandler.obtainMessage(arg0, "开启轨迹服务回调接口消息 [消息编码 : " + arg0 + "，消息内容 : " + arg1 + "]").sendToTarget();
            }

            // 轨迹服务推送接口（用于接收服务端推送消息，arg0 : 消息类型，arg1 : 消息内容，详情查看类参考）
            public void onTracePushCallback(byte arg0, String arg1) {
                if (0x03 == arg0 || 0x04 == arg0) {
                    try {
                        JSONObject dataJson = new JSONObject(arg1);
                        if (null != dataJson) {
                            String mPerson = dataJson.getString("monitored_person");
                            String action = dataJson.getInt("action") == 1 ? "进入" : "离开";
                            String date = DateUtils.getDate(dataJson.getInt("time"));
                            long fenceId = dataJson.getLong("fence_id");
//                            mHandler.obtainMessage(-1, "监控对象[" + mPerson + "]于" + date + " [" + action + "][" + fenceId + "号]围栏").sendToTarget();
                        }

                    } catch (JSONException e) {
//                        mHandler.obtainMessage(-1, "轨迹服务推送接口消息 [消息类型 : " + arg0 + "，消息内容 : " + arg1 + "]").sendToTarget();
                    }
                } else {
//                    mHandler.obtainMessage(-1, "轨迹服务推送接口消息 [消息类型 : " + arg0 + "，消息内容 : " + arg1 + "]").sendToTarget();
                }
            }

        };
    }

    /**
     * 初始化OnStopTraceListener
     */
    private void initOnStopTraceListener() {
        // 初始化stopTraceListener
        stopTraceListener = new OnStopTraceListener() {
            // 轨迹服务停止成功
            public void onStopTraceSuccess() {
//                mHandler.obtainMessage(1, "停止轨迹服务成功").sendToTarget();
                startRefreshThread(false);
                trackApp.getClient().onDestroy();
            }

            // 轨迹服务停止失败（arg0 : 错误编码，arg1 : 消息内容，详情查看类参考）
            public void onStopTraceFailed(int arg0, String arg1) {
//                mHandler.obtainMessage(-1, "停止轨迹服务接口消息 [错误编码 : " + arg0 + "，消息内容 : " + arg1 + "]").sendToTarget();
                startRefreshThread(false);
            }
        };
    }

    protected void startRefreshThread(boolean isStart) {
        if (null == refreshThread) {
            refreshThread = new RefreshThread();
        }
        refreshThread.refresh = isStart;
        if (isStart) {
            if (!refreshThread.isAlive()) {
                refreshThread.start();
            }
        } else {
            refreshThread = null;
        }
    }


    protected class RefreshThread extends Thread {
        protected boolean refresh = true;

        @Override
        public void run() {
            Looper.prepare();
            while (refresh) {
                // 轨迹服务开启成功后，调用queryEntityList()查询最新轨迹；
                // 未开启轨迹服务时，调用queryRealtimeLoc()进行实时定位。
                if (isTraceStarted) {

                } else {
                    aboutYing();
                }
                try {
                    Thread.sleep(gatherInterval * 1000);
                } catch (InterruptedException e) {
                    System.out.println("线程休眠失败");
                }
            }
            Looper.loop();
        }
    }

    /**
     * 初始化OnEntityListener
     */
    private void initOnEntityListener() {
        entityListener = new OnEntityListener() {
            // 请求失败回调接口
            @Override
            public void onRequestFailedCallback(String arg0) {
                trackApp.getmHandler().obtainMessage(0, "entity请求失败回调接口消息 : " + arg0).sendToTarget();
            }

            // 添加entity回调接口
            public void onAddEntityCallback(String arg0) {
                trackApp.getmHandler().obtainMessage(0, "添加entity回调接口消息 : " + arg0).sendToTarget();
            }

            // 查询entity列表回调接口
            @Override
            public void onQueryEntityListCallback(String message) {
                TraceLocation entityLocation = new TraceLocation();
                try {
                    JSONObject dataJson = new JSONObject(message);
                    if (dataJson.has("status") && dataJson.getInt("status") == 0
                            && dataJson.has("size") && dataJson.getInt("size") > 0) {
                        JSONArray entities = dataJson.getJSONArray("entities");
                        JSONObject entity = entities.getJSONObject(0);
                        JSONObject point = entity.getJSONObject("realtime_point");
                        JSONArray location = point.getJSONArray("location");
                        entityLocation.setLongitude(location.getDouble(0));
                        entityLocation.setLatitude(location.getDouble(1));
                    }
                } catch (JSONException e) {
                    trackApp.getmHandler().obtainMessage(0, "解析entityList回调消息失败").sendToTarget();
                    return;
                }
            }

            @Override
            public void onReceiveLocation(TraceLocation location) {

            }

        };
    }

    /**
     * 开启轨迹服务
     */
    private void startTrace() {
        trackApp = (MyApplication) getApplicationContext();
        // 通过轨迹服务客户端client开启轨迹服务
        trackApp.getClient().startTrace(trackApp.getTrace(), startTraceListener);
        if (!MonitorService.isRunning) {
            // 开启监听service
            MonitorService.isCheck = true;
            MonitorService.isRunning = true;
            startMonitorService();
        }
    }

    public void startMonitorService() {
        serviceIntent = new Intent(trackApp, MonitorService.class);
        trackApp.startService(serviceIntent);
    }


}
